    //
//  PlayerViewController.m
//  SHEL
//
//  Created by Jennifer Guriel on 11/3/11.
//  Copyright 2011 Washington University. All rights reserved.
//

#import "PlayerViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "PlayerDetailViewController.h"

#define MAX_COLS 5
#define RED 3
#define YELLOW 2
#define GREEN 1
#define GREY 0

@implementation PlayerViewController

@synthesize topBarLabel;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
		
		self.title = @"Icon View";
		self.navigationItem.title = @"Team SHEL";
		self.tabBarItem.image = [UIImage imageNamed:@"helmet_icon2.png"];
    }
    return self;
}


/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSDateFormatter *date_formater=[[NSDateFormatter alloc] init];
	[date_formater setDateFormat:@"EE, MMM dd"];
	NSString* sDate = [date_formater stringFromDate:[NSDate date]];
	[date_formater release];
	
	topBarLabel.text = [sDate stringByAppendingString:@" - Red vs Blue"];
	topBarLabel.textAlignment = UITextAlignmentRight;
	topBarLabel.backgroundColor = [UIColor grayColor];
	topBarLabel.layer.borderColor = [UIColor blackColor].CGColor;
	topBarLabel.layer.borderWidth = 1.0;
	
	if (playerData == nil) {
		playerData = [[NSMutableArray alloc] init];
	}
	if (playerHistory == nil) {
		playerHistory = [[NSMutableArray alloc] init];
	}
	if (hitCountList == nil) {
		hitCountList = [[NSMutableArray alloc] init];
	}
	if (playerIcons == nil) {
		playerIcons = [[NSMutableArray alloc] init];
	}
	if (shakeState == nil) {
		shakeState = [[NSMutableArray alloc] init];
	}
	if (playerTrauma == nil) {
		playerTrauma = [[NSMutableArray alloc] init];
	}
	
	// Periodically update shaking helmets
	[NSTimer scheduledTimerWithTimeInterval:0.1
									 target:self
								   selector:@selector(updateShakeState:)
								   userInfo:nil
									repeats:YES];
}


-(void) updatePlayerData:(NSArray*)data {

	if (playerIcons != nil)
	{
		// Determine if icons need to be added or removed
		if ([playerIcons count] > [data count])
		{
			int diff = [playerIcons count] - [data count];
			for (int i=0; i<diff; i++)
			{
				[[playerIcons lastObject] removeFromSuperview];
				[playerIcons removeLastObject];
				[shakeState removeLastObject];
			}
		}
		else if ([playerIcons count] < [data count])
		{
			int diff = [data count] - [playerIcons count];
			UIButton* button;
			UIImage* buttonImage;
			for (int i=0; i<diff; i++)
			{
				// the space between the image and text
				CGFloat spacing = -3.0;
				
				buttonImage = [UIImage imageNamed:@"grey_helmet_sm.png"];
				button = [UIButton buttonWithType:UIButtonTypeCustom];
				button.imageView.frame = CGRectMake(0,0, buttonImage.size.width, buttonImage.size.height);
				button.titleLabel.frame = CGRectMake(0,0, 15, 10);
				button.frame = CGRectMake(0,0, (button.imageView.frame.size.width + button.titleLabel.frame.size.width + spacing), 
										       (button.imageView.frame.size.height + button.titleLabel.frame.size.height + spacing));
				[button setCenter: [self getButtonPosition:[playerIcons count] buttonSize:buttonImage.size]]; 
				button.tag = 0;
				[button setImage:buttonImage forState:UIControlStateNormal];
				[button addTarget:self action:@selector(pushButton:) forControlEvents:UIControlEventTouchUpInside];
				
				[button setTitle:@"4" forState:UIControlStateNormal];
				[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
				[button.titleLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
				
				
				// get the size of the elements here for readability
				CGSize imageSize = button.imageView.frame.size;
				CGSize titleSize = button.titleLabel.frame.size;
				
				// get the height they will take up as a unit
				CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
				
				// raise the image and push it right to center it
				button.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
				
				// lower the text and push it left to center it
				button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height), 15.0);
				
				// Add to array and to view
				[playerIcons addObject:button];
				[self.view addSubview:button];
				
				// Keeps track of whether the object is shaking
				[shakeState addObject:[NSNumber numberWithInt:0]];
			}
		}
		
		// Update all of the icons
		for (int i = 0; i<[playerIcons count]; i++) {
			UIButton* icon = [playerIcons objectAtIndex:i];
			
			// Player number
			id number = [[data objectAtIndex:i] objectForKey:@"number"];
			if ([number intValue] < 10) 
			{
				[icon setTitle:[NSString stringWithFormat:@"0%@", [number stringValue]] forState:UIControlStateNormal];
			}
			else {
				[icon setTitle:[NSString stringWithFormat:@"%d", [number intValue]] forState:UIControlStateNormal];
			}
			[icon setTag:i];
		}
	}
}

-(void) updatePlayerHistory:(int)index {
	
	// Reset the flags
	if (index == 0) {
		if (redPresent) {
			previousState = RED;
		}
		else if (yellowPresent) {
		    previousState = YELLOW;
		}
		else if (greenPresent) {
			previousState = GREEN;
		}
		else if (greyPresent) {
		    previousState = GREY;
		}
		greenPresent = FALSE;
		redPresent = FALSE;
		yellowPresent = FALSE;
		greyPresent = FALSE;
	}
	
	// Update the corresponding icon
	UIButton* icon = [playerIcons objectAtIndex:index];
		
	UIImage* buttonImage;
	
	Boolean historyRecordIsToday = FALSE;
	
	if (playerHistory == nil || [playerHistory count] == 0 || [playerHistory objectAtIndex:0] == nil ||
		[playerHistory count] <= index||
		[playerHistory objectAtIndex:index] == nil || [[playerHistory objectAtIndex:index] count] == 0 ||
		[[playerHistory objectAtIndex:index] objectAtIndex:0] == nil)
	{
		historyRecordIsToday = FALSE;
	}
	else {
		NSString* historyDate = [[[[playerHistory objectAtIndex:index] objectAtIndex:0] objectForKey:@"date"] substringToIndex:10];
		//NSLog(@"1) %@", historyDate);
		
		NSDateFormatter *date_formater=[[NSDateFormatter alloc] init];
		[date_formater setDateFormat:@"YYY-MM-dd"];
		NSString* sDate = [date_formater stringFromDate:[NSDate date]];
		[date_formater release];
		//NSLog(@"2) %@",sDate);
		
		if ([historyDate isEqualToString:sDate])
		{
			historyRecordIsToday = TRUE;
			//NSLog(@"match!");
		}
	}
	
	
	// Color of a helmet is based on status value in history
	if (historyRecordIsToday) {
		// null = no history collected so disconnected
		if ([[[[playerHistory objectAtIndex:index] objectAtIndex:0] objectForKey:@"status"] intValue] == 0) {
			buttonImage = [UIImage imageNamed:@"grey_helmet_sm.png"];
			greyPresent = TRUE;
		}
		else if ([[[[playerHistory objectAtIndex:index] objectAtIndex:0] objectForKey:@"status"] intValue] == 1) {
			buttonImage = [UIImage imageNamed:@"green_helmet_sm.png"];
			greenPresent = TRUE;
		}
		else if ([[[[playerHistory objectAtIndex:index] objectAtIndex:0] objectForKey:@"status"] intValue] == 2) {
			buttonImage = [UIImage imageNamed:@"yellow_helmet_sm.png"];
			yellowPresent = TRUE;
		}
		else {
			buttonImage = [UIImage imageNamed:@"red_helmet_sm.png"];
			redPresent = TRUE;
		}
	}
	else {
		buttonImage = [UIImage imageNamed:@"grey_helmet_sm.png"];
	}
	
	[icon setImage:buttonImage forState:UIControlStateNormal];
		
	// Update the color of the top bar
	if (redPresent) {
		topBarLabel.backgroundColor = [UIColor redColor];
	}
	else if (yellowPresent && previousState != RED) {
		topBarLabel.backgroundColor = [UIColor yellowColor];
	}
	else if (greenPresent && previousState != RED && previousState != YELLOW) {
		topBarLabel.backgroundColor = [UIColor greenColor];
	}
	else if (greyPresent && previousState == GREY) {
		topBarLabel.backgroundColor = [UIColor grayColor];
	}
}

-(CGPoint) getButtonPosition:(int)index buttonSize:(CGSize)size {

	int spacingX = 12;
	int spacingY = 15;
	int col = index;
	int row = 0;
	
	while (col >= MAX_COLS)
	{
		col -= MAX_COLS;
		row++;
	}
	
	int x = ((size.width / 2)) + spacingX + (col * (size.width + spacingX));

	int y = topBarLabel.frame.size.height + spacingY + (size.height/2)  + ((size.height + spacingY) * row);
	
	return CGPointMake(x,y);
}

-(void) pushButton:(id)sender {
	NSString* lastname = [[playerData objectAtIndex:[sender tag]] objectForKey:@"lastname"];
	NSString* number = [[playerData objectAtIndex:[sender tag]] objectForKey:@"number"];
	NSString* nameStr = [NSString stringWithFormat:@"#%@ - %@", number, lastname];
	
	NSMutableArray* availHistory = nil;
	if ([playerHistory count] > [sender tag])
	{
		availHistory = [playerHistory objectAtIndex:[sender tag]];
	}
	NSMutableArray* availTrauma = nil;
	if ([playerTrauma count] > [sender tag])
	{
		availTrauma = [playerTrauma objectAtIndex:[sender tag]];
	}
	
	PlayerDetailViewController *detailViewController = [[PlayerDetailViewController alloc] initWithNibNameAndIndex:@"PlayerDetailViewController" bundle:nil 
																											 index:[sender tag]
																											  name:nameStr
																										   history:availHistory
																											trauma:availTrauma];
	
	[self.navigationController pushViewController:detailViewController animated:YES];
	[detailViewController release];
}

-(void) addPlayerHistory:(int)index history:(NSArray*)history {
	if ([playerHistory count] == 0 || [playerHistory count] < index+1) {
		[playerHistory addObject:history];
		if (history != nil) {
			[hitCountList addObject:[NSNumber numberWithInt:
									 [[[history objectAtIndex:0] objectForKey:@"hits"] intValue]
									 ]];
		}
		else {
			[hitCountList addObject:[NSNumber numberWithInt:0]];
		}
	}
	else {
		[playerHistory replaceObjectAtIndex:index withObject:history];
		
		int previousHits = [[hitCountList objectAtIndex:index] intValue];
		int currentHits = [[[[playerHistory objectAtIndex:index] objectAtIndex:0] objectForKey:@"hits"] intValue];
		
		if (previousHits != currentHits) {
			[self shakeHelmet:index];
		}
		
		[hitCountList replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:currentHits]];
	}
	
	[self updatePlayerHistory:index];
}

-(void) addPlayerTrauma:(int)index trauma:(NSArray*)trauma {
	if ([playerTrauma count] == 0 || [playerTrauma count] < index+1) {
		[playerTrauma addObject:trauma];
	}
	else {
		[playerTrauma replaceObjectAtIndex:index withObject:trauma];
	}
}

-(void) setPlayerData:(NSMutableArray*) data {
	playerData = data;
}

-(void) shakeHelmet:(int)index {
	//NSLog(@"shaking helmet!");
	[shakeState replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:1]];
}

// Moves all of the helmets that are currently shaking
-(void) updateShakeState:(NSTimer*)timer {
	for (int i=0; i<[playerIcons count]; i++) {
		if ([shakeState count] > i) {
			UIButton *btn = [playerIcons objectAtIndex:i];
			CGPoint center = btn.center;
			int state = [[shakeState objectAtIndex:i] intValue];
			switch (state) {
				case 1:
				case 5:
					center.y += 3;
					break;
				case 2:
				case 6:
					center.y += 3;
					break;
				case 3:
				case 7:
					center.y -= 3;
					break;
				case 4:
				case 8:
					center.y -= 3;
					break;
				default:
					break;
			}
			[btn setCenter:center];
			if (state == 8 || state == 0) {
				[shakeState replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:0]];
			}
			else {
				[shakeState replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:state+1]];
			}
		}
	}
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[playerIcons release];
	[playerHistory release];
	[playerTrauma release];
	[playerData release];
	[hitCountList release];
	[shakeState release];
}


@end
